package com.tcs.reptile.concurrent;

import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Maps;
import com.tcs.model.IpBean;
import com.tcs.model.email.MailSenderInfo;
import com.tcs.model.stock.StockBean;
import com.tcs.reptile.accept.Accept;
import com.tcs.reptile.proxyip.ProxyIpService;
import com.tcs.rpc.service.IEmailService;
import com.tcs.server.stock.IStockService;
import com.tcs.util.constant.SystemConstants;
import com.tcs.util.spring.SpringConfigTool;
import com.tcs.util.uuid.UUIDUtil;

public abstract class AbstractStockTask implements ConcurrentInterface {
	
	private final Logger logger = LoggerFactory.getLogger(AbstractStockTask.class);
	
	protected String url;

	protected int maxId;

	protected IStockService iStockService;

	protected IEmailService iEmailService;

	protected MailSenderInfo mailInfo;

	protected String[] Ccs;

	protected CountDownLatch countDownLatch;

	protected AtomicInteger atomicInteger;
	
	protected ProxyIpService proxyIpService;
	
	protected Accept accept;
	
	@Override
	public void job() throws Exception {
		IpBean ipBean = proxyIpService.getChargeVPSProxyIp();
		if (ipIsNull(ipBean)) {
			StockBean stockBean = null;
			Map<String,String> params = Maps.newHashMap();
			params.put(SystemConstants.ReptileConstants.URL, url);
			Document document = Jsoup.connect(getUrl(url, maxId))
					.headers(accept.getAccecptHeader(params))
					.proxy(ipBean.getIp(), ipBean.getPort())
					.get();
			document.select("img").remove();
			Elements main = document.select(".tableMain");
			logger.info(" --------- url : {} \n , title : {} \n, content : {}", getUrl(url, maxId), document.title(), main);
			String isOrNull = main.select("ul.tableContain span.tableTdVal").first().html();
			if (StringUtils.isNotBlank(isOrNull)) {
				stockBean = new StockBean(UUIDUtil.getUUID(), document.title(), main.outerHtml(), maxId);
				this.sendMessage(stockBean);
				try {
					iStockService.addStockModel(stockBean);
				} catch (Exception e) {
					logger.error(" 第一次入库 录入失败 : \n  stockBean : " + stockBean, e);
					try {
						stockBean.setContent("");
						iStockService.addStockModel(stockBean);
					} catch (Exception e1) {
						logger.error(" 第二次入库 录入失败 : \n  stockBean : " + stockBean, e1);
					}
				}
			}
		} else {
			logger.error(" 获取IP失败!!" ,new RuntimeException("结束运行"));
		}
	}
	
	protected AbstractStockTask(String url, int maxId, IStockService iStockService, IEmailService iEmailService) {
		super();
		this.url = url;
		this.maxId = maxId;
		this.iStockService = iStockService;
		this.iEmailService = iEmailService;
	}

	protected AbstractStockTask(String url, int maxId, IStockService iStockService, IEmailService iEmailService,
			MailSenderInfo mailInfo, String[] ccs) {
		super();
		this.url = url;
		this.maxId = maxId;
		this.iStockService = iStockService;
		this.iEmailService = iEmailService;
		this.mailInfo = mailInfo;
		this.Ccs = ccs;
	}

	protected AbstractStockTask(String url, int maxId, IStockService iStockService, IEmailService iEmailService,
			MailSenderInfo mailInfo, String[] ccs, CountDownLatch countDownLatch, AtomicInteger atomicInteger) {
		super();
		this.url = url;
		this.maxId = maxId;
		this.iStockService = iStockService;
		this.iEmailService = iEmailService;
		this.mailInfo = mailInfo;
		this.Ccs = ccs;
		this.countDownLatch = countDownLatch;
		this.atomicInteger = atomicInteger;
		this.proxyIpService = SpringConfigTool.getBean(ProxyIpService.class);
	}
	
	protected AbstractStockTask(String url, int maxId, IStockService iStockService, IEmailService iEmailService,
			MailSenderInfo mailInfo, String[] ccs, CountDownLatch countDownLatch, AtomicInteger atomicInteger,Accept accept) {
		super();
		this.url = url;
		this.maxId = maxId;
		this.iStockService = iStockService;
		this.iEmailService = iEmailService;
		this.mailInfo = mailInfo;
		this.Ccs = ccs;
		this.countDownLatch = countDownLatch;
		this.atomicInteger = atomicInteger;
		this.proxyIpService = SpringConfigTool.getBean(ProxyIpService.class);
		this.accept = accept;
	}

	protected AbstractStockTask() {};
	
	/**
	 * 拼接URL
	 * @Title: getUrl
	 * @Description: 组装URL
	 * @param url
	 * @param params
	 * @return {@link String}
	 */
	protected String getUrl(String url, Object params) {
		StringBuffer urlSb = new StringBuffer(url).append(params.toString());
		return urlSb.toString();
	}
	
	@Override
	public void over() {
		countDownLatch.countDown();
		atomicInteger.incrementAndGet();
	}
	
	private void sendMessage(StockBean stockBean) {
		this.setMailSenderInfo(stockBean);
		this.sendMessage();
	}

	private void setMailSenderInfo(StockBean stockBean) {
		mailInfo = new MailSenderInfo();
		mailInfo.setSubject(stockBean.getTitle());
		mailInfo.setSendFlag(SystemConstants.ReptileConstants.SENDEMAILHTML); // HTML 格式
		mailInfo.setContent(stockBean.getTitle() + "<br>" + stockBean.getContent());
		mailInfo.setCcs(Ccs);
	}
	
	protected void work() {
		try {
			this.job();
		} catch (Exception e) {
			logger.error("" , e);
		} finally {
			this.over();
		}
	}

	private void sendMessage() {
		try {
			if (null != mailInfo) {
				iEmailService.send(mailInfo);
				logger.info("发送成功! 数据为 : {} ", mailInfo);
			}
		} catch (Exception e) {
			logger.error("" , e);
		}
	}
	
	private boolean ipIsNull(IpBean ipBean) {
		boolean result = false;
		if (StringUtils.isNotBlank(ipBean.getIp()) && ipBean.getPort() > 0) {
			result = true;
		}
		return result;
	}
}